package com.java.advance.simple.threadpool;

import java.math.BigDecimal;

/**
 * 等额本金计算法
 * Created by yangminghua on 2019/2/21.
 */
public class Demo {

    public static void main(String[] orgs) throws Exception {
        //总本金
        BigDecimal applyAmount = new BigDecimal("5000");
        //利息利率
        BigDecimal interestRate = new BigDecimal("0.0075");
        Integer applyStages = 6;
        BigDecimal noRepayAmount = applyAmount;//未还本金
        BigDecimal currentAmount; //本月本金
        BigDecimal currentInterestFee;//本月利息
        System.out.println("借款金额: "+ applyAmount+"  利息利率: "+ interestRate);

        //本月本息
        BigDecimal currentRepayAndInterestAmount = applyAmount.multiply(interestRate.multiply(
                BigDecimal.valueOf(Math.pow(BigDecimal.ONE.add(interestRate).doubleValue(),applyStages))))
                .divide(BigDecimal.valueOf(Math.pow(BigDecimal.ONE.add(interestRate).
                        doubleValue(),applyStages)-1),2, BigDecimal.ROUND_HALF_UP);

        System.out.println("每月本息: "+ currentRepayAndInterestAmount);
        //
        for(int i = 1 ; i<=applyStages ; i++){
            //本月利息=未还本金*利息利率
            currentInterestFee = noRepayAmount.multiply(interestRate).setScale(2, BigDecimal.ROUND_HALF_UP);
            //最后一期
            if(i==applyStages){
                //本月本金=未还本金
                currentAmount = noRepayAmount;
                System.out.println("第"+i+"期，本金:"+currentAmount+"，利息:"+currentInterestFee);
                System.out.println("第"+i+"期本息:"+ currentAmount.add(currentInterestFee));
                noRepayAmount = noRepayAmount.subtract(noRepayAmount);
            }else {
                //本月本金=本月本息-本月利息
                currentAmount = currentRepayAndInterestAmount.subtract(noRepayAmount.multiply(interestRate)).
                        setScale(2, BigDecimal.ROUND_HALF_UP);
                System.out.println("第"+i+"期，本金:"+currentAmount+"，利息:"+currentInterestFee);
                System.out.println("第"+i+"期本息:"+ currentAmount.add(currentInterestFee));
                //未还本金-本月本金
                noRepayAmount = noRepayAmount.subtract(currentAmount);
            }
            System.out.println("第"+i+"期，未还本金:"+noRepayAmount);
        }
    }

}
